package com.fosu.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.fosu.common.ResponseResult;
import com.fosu.dao.CommentDao;
import com.fosu.dao.UserDao;
import com.fosu.domain.Comment;
import com.fosu.service.CommentService;
import com.fosu.vo.UserCommentTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Desription
 * 评论业务实现类
 *
 * @author manno
 * @date 2020/10/19
 */
@Service
@Transactional
public class CommentServiceImpl implements CommentService {
    @Autowired
    private CommentDao commentDao;
    @Autowired
    private UserDao userDao;

    @Override
    public ResponseResult findProductComments(HttpServletResponse resp, int currentPage, int pageSize, int productId) {
        currentPage = (currentPage - 1) * pageSize;
        List<Comment> comments = commentDao.findProductComments(currentPage, pageSize, productId);
        if (comments.size() == 0) {
            return ResponseResult.build(resp, 500, 10003, "没有更多评论了", comments);
        }
        for (Comment c : comments) {
            getReplies(c, c, c.getReplies());
        }
        return ResponseResult.build(resp, 200, 10002, "获取商品评论成功", comments);
    }

    @Override
    public List<Comment> findReplies(int commentId) {

        return this.commentDao.findReplies(commentId);
    }

    @Override
    public ResponseResult findIsFavorite(HttpServletResponse resp, Integer userId, Integer commentId) {
        try {
            if (commentDao.findIsFavorite(userId, commentId) != 0) {
                return ResponseResult.build(resp, 200, 10004, "点赞状态：已点赞", null);
            } else {
                return ResponseResult.build(resp, 200, 10005, "点赞状态：未点赞", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.build(resp, 500, 10010, "获取点赞状态失败", null);
        }

    }

    @Override
    @Transactional
    public ResponseResult switchWhetherToFavorite(HttpServletResponse resp, Integer userId, Integer commentId)
    {
        try {
            /**如果已经点赞*/
            if (commentDao.findIsFavorite(userId, commentId) != 0) {
                /**移除点赞*/
                commentDao.removeFavorite(userId, commentId);
                commentDao.decFavoriteCount(commentId);
                return ResponseResult.build(resp,200,30006,"切换评论点赞状态：成功切换",null);
            }else {
                /**点赞*/
                commentDao.addFavorite(userId, commentId);
                commentDao.addFavoriteCount(commentId);
                return ResponseResult.build(resp,200,30006,"切换评论点赞状态：成功切换",null);
            }
        }catch (Exception e)
        {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ResponseResult.build(resp, 500, 30007, "切换评论点赞状态：切换失败", null);
    }

    /**
     * 获得评论的所有回复
     */
    void getReplies(Comment topComment, Comment currComment, List<Comment> totalReplies) {
        if (totalReplies == null) {
            totalReplies = new ArrayList<>();
        }
        System.out.println("当前正在查找===>" + currComment + "下的回复");
        /**获得当前评论的所有回复*/
        List<Comment> replies = commentDao.findReplies(currComment.getCommentId());
        for (Comment c : replies) {
            totalReplies.add(c);
            System.out.println("totalReplies : " + totalReplies);
        }
        /**如果当前评论有回复就查看回复中是否仍有回复*/
        if (replies == null || isNoReplies(replies)) {
            topComment.setReplies(totalReplies);
        } else if (replies != null && !isNoReplies(replies)) {
            for (Comment reply : replies) {
                getReplies(topComment, reply, totalReplies);
            }
            System.out.println(replies);
            topComment.setReplies(totalReplies);
        } else {
//                topComment.setReplies(null);
        }

    }

    /**
     * 检查是否还有回复，有就返回true
     */
    boolean isNoReplies(List<Comment> replies) {
        boolean isNoReplies = true;
        for (Comment reply : replies) {
            if (commentDao.findReplies(reply.getCommentId()) != null) {
                isNoReplies = false;
            }
        }
        return isNoReplies;
    }

    /*保存评论*/
    @Override
    public ResponseResult saveComment(HttpServletResponse resp, JSONObject jsonPram){
        Comment comment = new Comment();
        int ownerUserId = -1;
        Integer targetCommetId = -1;
        String content = null;
        int productId = -1;
        /**检测数据是否符合规范*/
        try {
            ownerUserId = jsonPram.getIntValue("ownerUserId");
            if(ownerUserId != -1)
            {
                comment.setOwnerUserId(ownerUserId);
            }
            targetCommetId = jsonPram.getIntValue("targetCommetId");
            if(targetCommetId == 0 || targetCommetId==null)
            {
                comment.setTargetCommentId(-1);
            }else {
                comment.setTargetCommentId(targetCommetId);
            }
            content = jsonPram.getString("content");
            if(content != null)
            {
                comment.setContent(content);
            }else {
                return ResponseResult.build(resp,500,30030, "评论内容为空",null);
            }
            productId = jsonPram.getIntValue("productId");
            if(productId != -1)
            {
                comment.setProductId(productId);
            }else {
                return ResponseResult.build(resp,500,30033, "商品id为空",null);
            }
            /**保存*/
            commentDao.saveComment(comment);
        } catch (RuntimeException e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.build(resp,500,30032, "发布评论失败",null);
        }

        return ResponseResult.build(resp,200,30031, "发布评论成功",null);
    }

    @Override
    public ResponseResult getFavoriteCommentByUserId(HttpServletResponse resp, Integer userId) {
        List<Comment> favoriteCommentByUserIdList = null;
        try {
            favoriteCommentByUserIdList = commentDao.getFavoriteCommentByUserId(userId);
            if (favoriteCommentByUserIdList.size() == 0 || favoriteCommentByUserIdList == null) {
                return ResponseResult.fail(resp, "回复的评论为空或找不到");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail(resp, "获取评论信息失败");
        }
        return ResponseResult.ok(resp, "获取评论信息成功", favoriteCommentByUserIdList);
    }

    @Override
    public ResponseResult getReplyToMECount(HttpServletResponse resp, Integer userId)
    {
        try
        {
            return ResponseResult.build(resp,200,10030,"按用户id获取回复我的总数成功", commentDao.getReplyToMECount(userId));
        }catch (RuntimeException e)
        {
            e.printStackTrace();
            return ResponseResult.build(resp,500,10031,"按用户id获取回复我的总数失败", commentDao.getReplyToMECount(userId));
        }
    }


    /**
     * 获取回复我的新增数量
     *
     * @param resp
     * @param userId
     * @return
     */
    @Override
    public ResponseResult getRecentlyReplyToMECount(HttpServletResponse resp, Integer userId) throws Exception {

        Date lastCommentTime = null;
        Date clickReplyToMeTime = null;
        String lastCommentTime1 = null;
        String format = null;
        String format2 = null;
        Integer count = null;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            lastCommentTime = userDao.getLastCommentTime(userId);//获取点击回复我的后 记录的时间
            clickReplyToMeTime = commentDao.getLastCommentTime(userId);//获取最后评论时间
            format = simpleDateFormat.format(clickReplyToMeTime);//获取点击回复我的后 记录的时间
            lastCommentTime1 = simpleDateFormat.format(lastCommentTime);//某用户最后被评论时间

            Date minDate = new Date(Long.MIN_VALUE);
            format2 = simpleDateFormat.format(minDate);
            count = commentDao.getRecentlyReplyToMECount(format2, format, userId);//获取回复我的数量
            return ResponseResult.build(resp,200,10032,"获取新增回复数量成功",count);



        } catch (Exception e) {
            return ResponseResult.build(resp,500,10033,"获取新增回复数量失败",count);
        }


    }
}
